﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;

using CloudSoft.Extensions;

namespace ERPStore.Localization.Controllers
{
	public class LocalizationController : Controller
	{
		public LocalizationController(ERPStore.Services.ILocalizationService localizationService)
		{
			this.LocalizationService = localizationService;
		}

		protected ERPStore.Services.ILocalizationService LocalizationService { get; private set; }

		public ActionResult Script()
		{
			var token = Request["translate"]; 
			if (token != LocalizationService.Token)
			{
				return new EmptyResult();
			}

			var result = new System.Text.StringBuilder();
			result.Append("<script src=\"/scripts/jquery.contextMenu.js\" type=\"text/javascript\"></script>");
			result.Append("<link href=\"/content/jquery.contextMenu.css\" rel=\"stylesheet\" type=\"text/css\" />");
			result.AppendFormat("<script type=\"text/javascript\">\r\n{0}\r\n</script>", GetEmbeddedScript("Localization.js"));
			return Content(result.ToString());
		}

		public ActionResult Content(string path, string key, string token, string defaultContent, string viewName)
		{
			if (!token.IsNullOrTrimmedEmpty())
			{
				var parts = token.Split('#');
				if (parts.Length > 1)
				{
					token = parts[0];
				}
			}
			if (token != this.LocalizationService.Token)
			{
				throw new ArgumentException("bad token");
			}

			var contentToLocalize = new Models.ContentToLocalize();
			contentToLocalize.Key = key;
			contentToLocalize.Path = path;
			contentToLocalize.DefaultContent = defaultContent;
			contentToLocalize.Token = token;

			foreach (var item in LocalizationService.SupportedLanguageList)
			{
				var value = LocalizationService.GetLocalizedContent(path, item, null, key, defaultContent, ERPStore.Models.LocalizedContentType.Label);
				contentToLocalize.LocalizationByLanguage.Add(item, value);
			}

			if (viewName.IsNullOrTrimmedEmpty())
			{
				return GetStaticContent(contentToLocalize);
			}
			ViewData.Model = contentToLocalize;
			return View(viewName);
		}

		internal ActionResult GetStaticContent(Models.ContentToLocalize content)
		{
			var sb = new StringBuilder();
			sb.Append("<div>");
			sb.AppendFormat("<p>Translating : <strong>{0}</strong></p>", content.Key);
			sb.Append("<form name=\"saveTranslationForm\" action=\"/localize/SaveLocalizedContent\" method=\"post\">");
			sb.Append("<table>");
			sb.Append("<thead>");
			sb.Append("<tr>");
			sb.Append("<td>Language</td>");
			sb.Append("<td>Translation</td>");
			sb.Append("</tr>");
			sb.Append("</thead>");
			foreach (var item in content.LocalizationByLanguage)
			{
				sb.Append("<tr>");
				sb.AppendFormat("<td>{0}", item.Key);
				sb.AppendFormat("<input type=\"hidden\" name=\"lg\" value=\"{0}\"/>", item.Key);
				sb.Append("</td>");
                sb.AppendFormat("<td><textarea id=\"TextArea1\" cols=\"60\" rows=\"3\" name=\"value_{0}\">{1}</textarea></td>", item.Key , item.Value);
				sb.Append("</tr>");
			}
			sb.Append("</table>");
			sb.AppendFormat("<input type=\"hidden\" name=\"path\" value=\"{0}\" />", content.Path);
			sb.AppendFormat("<input type=\"hidden\" name=\"token\" value=\"{0}\" />", LocalizationService.Token);
			sb.AppendFormat("<input type=\"hidden\" name=\"key\" value=\"{0}\" />", content.Key);
			sb.Append("<input type=\"submit\" value=\"Save\" />");
			sb.Append("</form>");
			sb.Append("</div>");
			return Content(sb.ToString(), "text/html");
		}

		public ActionResult SaveLocalizedContent(FormCollection form)
		{
			string key = form["key"];
			var path = form["path"];
			var languages = form["lg"].Split(',');


			for (int i = 0; i < languages.Length; i++)
			{
				var language = languages[i];
                var value = form["value_" + language]; 
				LocalizationService.Save(path, language, key, value);
			}

			return Redirect(Request.UrlReferrer.PathAndQuery);
		}

		private string GetEmbeddedScript(string scriptName)
		{
			var assembly = System.Reflection.Assembly.GetExecutingAssembly();
			string result = null;
			using (var stream = assembly.GetManifestResourceStream("ERPStore.Localization.Scripts." + scriptName))
			{
				using (var sr = new System.IO.StreamReader(stream))
				{
					result = sr.ReadToEnd();
					sr.Close();
				}
			}
			return result;
		}
	}
}
